package com.codingapi.p2p.client.handler;

import com.codingapi.p2p.client.handler.peer.ByteEchoPeerOne;
import com.codingapi.p2p.client.service.NettyClientService;
import com.codingapi.p2p.client.service.NettyServerService;
import com.codingapi.p2p.client.service.impl.NettyClientServiceImpl;
import com.codingapi.p2p.client.service.impl.NettyServerServiceImpl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.internal.SocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * create by lorne on 2018/3/13
 */
public class DiscardClientHandler extends ChannelInboundHandlerAdapter{


    private Logger logger = LoggerFactory.getLogger(DiscardClientHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        logger.info("connection-->"+ctx.channel().localAddress());

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        logger.info("disconnection-->");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf =  (ByteBuf)msg;
        int length =  byteBuf.readableBytes();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        String str = new String(bytes);
        logger.info("read-->"+str);

        String self = str.split("\\:")[0];
        String host = str.split("\\:")[1];
        int port = Integer.parseInt(str.split("\\:")[2]);

        new Thread(){
            @Override
            public void run() {
//                super.run();
//                NettyServerService nettyServerService = new NettyServerServiceImpl(self,((InetSocketAddress)ctx.channel().localAddress()).getPort());
//                nettyServerService.start();
//
//                NettyClientService nettyClientService = new NettyClientServiceImpl(host,port);
//                nettyClientService.start();

                final InetSocketAddress myAddress = SocketUtils.socketAddress(((InetSocketAddress)ctx.channel().localAddress()).getHostName(), ((InetSocketAddress)ctx.channel().localAddress()).getPort());
                final InetSocketAddress peerAddress = SocketUtils.socketAddress(host,port);
                try {
                    new ByteEchoPeerOne( myAddress, peerAddress).run();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }
}
